<template>
  <div class="comm-comment comment-area" id="comment_area">
    <div class="comment-box">
      <div class="tit-num">评论 <i>{{ commentTotal }}</i></div>
      <div class="comment-inp" :class="{ 'active': isCommentFocus }">
        <textarea id="commentVal" @blur="isCommentFocus = false" v-model="commentVal"
          @focus="isCommentFocus = true; replyContent = ''; replyItem = {};" placeholder="说点什么吧..."></textarea>
      </div>
      <div class="send-box">
        <Face txtId="commentVal" mod="botsend" :offset="140" @change="(val) => { commentVal = val; }" />
        <a class="send-btn" @click="handleSend">评论</a>
      </div>
      <template v-if="isgame">
        <div class="call-box">
          <div class="left-persons">
            <template v-if="callmembertotal > 0">
              <div class="person">
                <a v-for="(u, idx) in callmembers"><img loading="lazy" :srcset="u.srcsets" v-lazy="u.lazy" @error="loadError"></a>
                <!-- <a><img loading="lazy" src="https://img.gameui.net/avatar-183-ac7ef0@1x50.webp" alt=""></a>
                <a><img loading="lazy" src="https://img.gameui.net/avatar-183-ac7ef0@1x50.webp" alt=""></a>
                <a><img loading="lazy" src="https://img.gameui.net/avatar-183-ac7ef0@1x50.webp" alt=""></a>
                <a><img loading="lazy" src="https://img.gameui.net/avatar-183-ac7ef0@1x50.webp" alt=""></a>
                <a><img loading="lazy" src="https://img.gameui.net/avatar-183-ac7ef0@1x50.webp" alt=""></a> -->
                <a class="last-more" v-if="callmembertotal > 6"></a>
              </div>
              <div class="call-mini-tip">{{ callmembertotal }}个人为TA打Call</div>
            </template>
          </div>
          <!-- <div class="call-btn">
            打call
          </div> -->

          <div class="call-mini-tip single-call-btn icon-container" @mousedown="callMousedown"
            @touchstart="callTouchStart">
            <div class="loading-indicator"></div>
            <i
              class="num total-count">{{ emdata.em1.num + emdata.em2.num + emdata.em3.num + emdata.em4.num + emdata.em5.num }}</i>
            <i class="text">打call</i>

            <div class="tech-border-outer"></div>
            <div class="tech-border-inner"></div>
            <div class="pulse-ring"></div>
          </div>
        </div>
        <div class="call-types">
          <el-popover popper-class="emo-info-pop" placement="top" trigger="hover">
              <span class="emo-s-tip" slot-content>
                  <i class="text">花花送给你</i>
              </span>
              <a slot="reference" class="call-type call-type-1" @click="handleCall(0)"><i class="num"
                  v-if="emdata.em1.num > 0">x{{ emdata.em1.num }}</i></a>
          </el-popover>
          <el-popover popper-class="emo-info-pop" placement="top" trigger="hover">
              <span class="emo-s-tip" slot-content>
                  <i class="text">礼物抱抱你</i>
              </span>
              <a slot="reference" class="call-type call-type-2" @click="handleCall(1)"><i class="num"
              v-if="emdata.em2.num > 0">x{{ emdata.em2.num }}</i></a>
          </el-popover>
          <el-popover popper-class="emo-info-pop" placement="top" trigger="hover">
              <span class="emo-s-tip" slot-content>
                  <i class="text">比心暖暖哒</i>
              </span>
              <a slot="reference" class="call-type call-type-3" @click="handleCall(2)"><i class="num"
              v-if="emdata.em3.num > 0">x{{ emdata.em3.num }}</i></a>
          </el-popover>
          <el-popover popper-class="emo-info-pop" placement="top" trigger="hover">
              <span class="emo-s-tip" slot-content>
                  <i class="text">来杯暖咖啡</i>
              </span>
              <a slot="reference" class="call-type call-type-4" @click="handleCall(3)"><i class="num"
              v-if="emdata.em4.num > 0">x{{ emdata.em4.num }}</i></a>
          </el-popover>
          <el-popover popper-class="emo-info-pop" placement="top" trigger="hover">
              <span class="emo-s-tip" slot-content>
                  <i class="text">一起冲冲冲</i>
              </span>
              <a slot="reference"  class="call-type call-type-5" @click="handleCall(4)"><i class="num"
              v-if="emdata.em5.num > 0">x{{ emdata.em5.num }}</i></a>
          </el-popover>

        </div>
      </template>
      <div class="comments">
        <div class="comment-data-item" v-for="(item, idx) in comments">
          <template v-if="item.member">
            <a class="uavatar" :href="'/user/' + item.member.id" target="_blank">
              <img loading="lazy" v-aimgd="{ avatar: item.member.avatar, id: item.member.id, w: 34, name: item.member.userName }">
            </a>
            <div class="r-con">
              <a class="name">{{ item.member.userName + (userId == item.member.id ? '（我的评论）' : '') }}</a>
              <div class="con-html" v-html="item.content"></div>
              <div class="bot">
                <span class="time">{{ item.intervalTimeStr }}</span>
                <div class="funs">
                  <a class="reply" @click="parentItem = {}; currentCmtIdx = idx; showDel = true;"
                    v-if="userId == item.member.id">删除</a>
                  <a class="reply" @click="item.showReply = true; replyItem = item; parentItem = item;">回复</a>
                  <a class="cmt-zan" :class="{ active: item.praiseCount > 0 }" @click="(e) => { handleZComment(item, e) }">{{
                    item.praise }}</a>
                </div>
              </div>
              <div class="comment-data-item child" v-for="(child, chx) in item.commentList"
                v-if="(child.content && chx < 3) || item.showallcmt">
                <span class="uavatar">
                  <img loading="lazy" v-aimgd="{ avatar: child.member.avatar, id: child.member.id, w: 34, name: child.member.userName }">
                </span>
                <div class="r-con">
                  <div class="name">{{ child.member.userName }}</div>
                  <div class="con-html" v-html="child.content"></div>
                  <div class="bot">
                    <span class="time">{{ child.intervalTimeStr }}</span>
                    <div class="funs">
                      <a class="reply" @click="parentItem = item; currentCmtIdx = chx; showDel = true;"
                        v-if="userId == child.member.id">删除</a>
                      <a class="reply" @click="child.showReply = true; replyItem = child; parentItem = item;">回复</a>
                      <a class="cmt-zan" @click="(e) => { handleZComment(child, e) }"
                        :class="{ active: child.praiseCount > 0 }">{{
                        child.praise }}</a>
                    </div>
                  </div>
                  <div class="reply-area" v-if="child.showReply && replyItem.id == child.id">
                    <div class="txt-area">
                      <textarea class="custom-scroll"
                        :placeholder="replyItem.id == child.id ? '回复 @' + replyItem.member.userName : '点赞是喜欢，评论是真爱～'"
                        maxlength="2000" :id="'commentVal_' + idx" name="" v-model="replyContent"></textarea>
                      <i>{{ replyContent.length }}/2000</i>
                    </div>
                    <div class="bot-area">
                      <Face :txtId="'commentVal_' + idx" :offset="140" mod="botsend"
                        @change="(val) => { replyContent = val; }" />
                      <a class="reply-btn" @click="handleReply">回复</a>
                    </div>
                  </div>
                </div>
              </div>
              <div class="view-all" v-if="item.commentList.length > 3 && !item.showallcmt">
                <a class="btn" @click="item.showallcmt = true; $forceUpdate();">显示 {{ item.commentList.length }} 条所有评论</a>
              </div>
              <div class="reply-area" v-if="item.showReply && replyItem.id == item.id">
                <div class="txt-area">
                  <textarea class="custom-scroll"
                    :placeholder="replyItem.id == item.id ? '回复 @' + replyItem.member.userName : '点赞是喜欢，评论是真爱～'"
                    maxlength="2000" :id="'commentVal_' + idx" name="" v-model="replyContent"></textarea>
                  <i>{{ replyContent.length }}/2000</i>
                </div>
                <div class="bot-area">
                  <Face :offset="140" :txtId="'commentVal_' + idx" mod="botsend"
                    @change="(val) => { replyContent = val; }" />
                  <a class="reply-btn" @click="handleReply">回复</a>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
      <div class="no-more-text" v-if="!hasMore && !isloading && comments.length > 0">没有更多了~</div>
    </div>

    <a-modal v-model="showDel" destroyOnClose centered :footer="null" :closable="false" width="366px">
      <div class="fav-component">
        <div class="fav-header">
          系统提示
        </div>
        <div class="folder-con" style="margin-top:30px;text-align:center;font-size:14px;">
          确定要删除？
        </div>
        <div class="btns m-widbtns">
          <a class="pro-default-btn" @click="showDel = false">取消</a>
          <a class="pro-confirm-btn" @click="handleConfirmDel">确认</a>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import api from '@/api/api'
import Face from '@/components/face'
export default {
  data() {
    return {
      emdata: {
        em1: { praiseCount: 0 },
        em2: { praiseCount: 0 },
        em3: { praiseCount: 0 },
        em4: { praiseCount: 0 },
        em5: { praiseCount: 0 }
      },
      isCommentFocus: false,
      isloading: true,
      scrollLoaded: false,
      hasMore: true,
      showDel: false,
      currentCmtIdx: '',
      parentItem: null,
      userId: '',
      commentTotal: '',
      commentVal: '',
      comments: [],
      replyItem: {},
      replyContent: '',
      params: {
        pageNum: 1,
        pageSize: 10,
        parentId: 0,
        commentId: '',
        orderByColumn: 'createTime',
        isAsc: 'desc'
      },
      fullScPraiseParam: {
        isAnimating: false,
        lastTime: 0,
        CONFIG: {
          particleCount: {
            mobile: 15,
            tablet: 20,
            desktop: 25
          },
          cooldown: 1500
        }
      }
    }
  },
  components: { Face },
  props: ['moduleId', 'callmembers', 'callmembertotal', 'isgame'],
  async mounted() {
    if (localStorage.getItem('token')) {
      this.userId = localStorage.getItem('userId');
      this.params.currentUserId = localStorage.getItem('userId');
    }
    this.params.commentId = this.moduleId;
    this.queryList();

    if (this.isgame)
      this.getCallTotal();
  },
  methods: {
    async getCallTotal() {
      let res = await api.getCallStatistics(this.moduleId);
      let obj = { em1: { num: 0, praiseCount: 0 }, em2: { num: 0, praiseCount: 0 }, em3: { num: 0, praiseCount: 0 }, em4: { num: 0, praiseCount: 0 }, em5: { num: 0, praiseCount: 0 } };

      if (res.data && res.data.length > 0) {
        let _em1 = res.data.filter(r => { return r.content == '[call_em_5]' });
        let _em2 = res.data.filter(r => { return r.content == '[call_em_17]' });
        let _em3 = res.data.filter(r => { return r.content == '[call_em_16]' });
        let _em4 = res.data.filter(r => { return r.content == '[call_em_20]' });
        let _em5 = res.data.filter(r => { return r.content == '[call_em_28]' });
        if (_em1 && _em1.length > 0) {
          obj.em1.num = _em1[0].num;
        }
        if (_em2 && _em2.length > 0) {
          obj.em2.num = _em2[0].num;
        }
        if (_em3 && _em3.length > 0) {
          obj.em3.num = _em3[0].num;
        }
        if (_em4 && _em4.length > 0) {
          obj.em4.num = _em4[0].num;
        }
        if (_em5 && _em5.length > 0) {
          obj.em5.num = _em5[0].num;
        }
      }
      this.emdata = obj;
    },
    callMousedown(e) {
      this.$parent.callMousedown(e);
    },
    callTouchStart(e) {
      this.$parent.callTouchStart(e);
    },
    async handleCall(_num) {
      let ckPass = this.$bhelper.checkLogin(this);
      if (!ckPass) return;
      let emoarray = [5, 17, 16, 20, 28];
      let emoStr = '[call_em_' + emoarray[_num] + ']';

      let res = await api.addComment({ parentId: 0, type: 0, commentStatus: 3, commentId: this.moduleId, content: emoStr, count: 1 })
      if (res.code == 0) {
        // 模拟服务器返回新的总数
        // this.callParam.totalCount += count;
        // this.updateTotalCount();
        this.emdata['em' + (_num + 1)].num += 1;
        this.$amessage.success('应援成功！气氛在燃烧')
        let id = 'd_call_img_' + Date.parse(new Date());
        $('.support-btn').append('<img loading="lazy" id="' + id + '" class="d-call-img" src="' + this.$webdomainurl + '/emoji/' + emoarray[_num] + '.svg' + '" alt="">');
        setTimeout(function () {
          $('.support-btn').find('#' + id).remove();
        }, 1500)

        this.$parent.createConfetti();
        this.$parent.getCallMembers();
      }
    },
    loadError(e) {
      e.target.removeAttribute('srcset');
    },
    handleEmoj() {

    },
    pushData(item) {
      item.commentList = [];
      this.comments = [...[item], ...this.comments];
    },
    loadMore() {
      this.params.pageNum++;
      this.queryList();
    },
    async handleConfirmDel() {
      let id = this.parentItem.id ? this.parentItem.commentList[this.currentCmtIdx].id : this.comments[this.currentCmtIdx].id;
      let res = await api.delComment(id);
      if (res.code == 0) {
        if (this.parentItem.id) {
          this.parentItem.commentList.splice(this.currentCmtIdx, 1);
        } else {
          this.comments.splice(this.currentCmtIdx, 1);
        }

        this.$emit('change', this.comments)
        this.$amessage.success('删除成功');
        this.showDel = false;
      }
    },
    async handleZComment(item, e) {
      let ckPass = this.$bhelper.checkLogin(this);
      if (!ckPass) return;
      let res = {};
      if (item.praiseCount > 0) {
        res = await api.delPraise({ type: 1, praiseId: item.id });
        if (res.code == 0) {
          item.praise--;
          item.praiseCount = 0;
          this.$amessage.success('取消喜欢~')
        }
      } else {
        res = await api.addPraise({ type: 1, praiseId: item.id });
        if (res.code == 0) {
          // this.createHearts(e.target);
          this.createPlusOne(e.target);
          item.praise++;
          item.praiseCount = 1;
          this.$amessage.success('已送出喜欢！也觉得说得很对')
        }
      }
    },
    getRandomNumber(min, max) {
      return Math.random() * (max - min) + min;
    },
    getParticleCount() {
      const width = window.innerWidth;
      if (width <= 480) return this.fullScPraiseParam.CONFIG.particleCount.mobile;
      if (width <= 768) return this.fullScPraiseParam.CONFIG.particleCount.tablet;
      return this.fullScPraiseParam.CONFIG.particleCount.desktop;
    },
    createHearts(e) {
      const confettiContainer = document.createElement('div');
      confettiContainer.className = 'confetti-container';

      let _parent = document.querySelector('.comp-article-page');
      if (location.href.indexOf('/game/') > -1) {
        _parent = document.querySelector('.game-page');
      } else if (location.href.indexOf('/article/') > -1) {
        _parent = document.querySelector('.comp-article-page');
      }
      _parent.appendChild(confettiContainer);

      const now = Date.now();
      if (this.fullScPraiseParam.isAnimating || now - this.fullScPraiseParam.lastTime < this.fullScPraiseParam.CONFIG.cooldown) return;

      this.fullScPraiseParam.isAnimating = true;
      this.fullScPraiseParam.lastTime = now;

      // showToast();

      // const btn =e.target;
      let that = this;
      // btn.style.animation = 'btn-success 0.5s ease';
      // setTimeout(() => btn.style.animation = '', 500);

      const particleCount = this.getParticleCount();
      const viewportWidth = window.innerWidth;
      const spacing = viewportWidth / particleCount;

      const fragment = document.createDocumentFragment();
      let activeParticles = particleCount;

      for (let i = 0; i < particleCount; i++) {
        const heart = document.createElement('div');
        heart.className = 'heart';
        heart.textContent = '❤';

        const xPos = i * spacing + this.getRandomNumber(-20, 20);
        heart.style.left = `${xPos}px`;

        const duration = this.getRandomNumber(2, 3);
        heart.style.animationDuration = `${duration}s`;

        heart.addEventListener('animationend', () => {
          heart.remove();
          if (--activeParticles === 0) {
            that.fullScPraiseParam.isAnimating = false;
          }
        }, { once: true });

        fragment.appendChild(heart);
      }

      confettiContainer.appendChild(fragment);
    },
    createPlusOne(likeContainer) {
      const plus = document.createElement('div');
      plus.className = 'plus-one';
      plus.innerHTML = '<span style="color: #ffffff;">+</span><span style="color: #ffffff;">1</span>';
      plus.style.left = '50%';
      plus.style.top = '50%';
      plus.style.animation = 'floatUp 1s cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards';

      likeContainer.appendChild(plus);
      setTimeout(() => plus.remove(), 1000);
    },
    async handleReply() {
      let ckPass = this.$bhelper.checkLogin(this);
      if (!ckPass) return;
      if (!this.replyContent) {
        this.$amessage.warn('请输入评论内容~');
        return;
      }
      let params = { type: 0, commentId: this.moduleId, content: this.replyContent };
      if (this.replyItem) {
        params.parentId = this.replyItem.id;
      }
      let res = await api.addComment(params);
      if (res.code == 0) {
        res.data.member = JSON.parse(decodeURIComponent(localStorage.getItem('BSIC')));
        res.data.content = this.$bhelper.replace_em(res.data.content);

        if (this.replyItem.id)
          res.data.parentName = this.replyItem.member.userName;

        this.parentItem.commentList = [...this.parentItem.commentList, ...[res.data]];

        this.replyItem = {};
        this.replyContent = '';
        this.$amessage.success('回复已送达，继续畅聊吧～');

        this.$emit('change', this.comments)
      }
    },
    async handleSend() {
      let ckPass = this.$bhelper.checkLogin(this);
      if (!ckPass) return;
      if (!this.commentVal) return;
      let res = await api.addComment({ type: 0, commentId: this.moduleId, content: this.commentVal });
      if (res.code == 0) {
        res.data.commentList = [];
        res.data.showReply = false;
        res.data.member = JSON.parse(decodeURIComponent(localStorage.getItem('BSIC')));
        res.data.content = this.$bhelper.replace_em(res.data.content);
        this.comments = [res.data].concat(this.comments);
        // this.comments.push(res.data);
        this.commentVal = '';
        this.$amessage.success('你的神评论已发射！')
        this.$emit('change', this.comments)
      }
    },
    async queryList() {
      let that = this;
      let res = await api.getComments(this.params);
      let list = res.data;
      this.commentTotal = res.total;
      this.scrollLoaded = false;
      this.isloading = true;
      list.forEach((l) => {
        l.content = that.$bhelper.replace_em(l.content);
        l.showSubMore = false;
        l.showReply = false;
        l.replayModel = {
          content: ''
        };
        if (l.commentList && l.commentList.length > 0) {
          l.commentList.forEach(s => {
            s.content = that.$bhelper.replace_em(s.content);
            s.showReply = false;
            s.replayModel = {
              content: ''
            };
          })
        }
      })
      let totalPage = res.total % that.params.pageSize == 0 ? res.total / that.params.pageSize : parseInt(res.total / that.params.pageSize) + 1;

      if (res.data && (res.data.length < that.params.pageSize || that.params.pageNum >= totalPage)) {
        that.hasMore = false;
      } else {
        that.hasMore = true;
      }
      this.isloading = false;
      this.scrollLoaded = true;
      this.comments = [...this.comments, ...list];

      this.$emit('change', this.comments)
    }
  }
}
</script>

<style lang="less">
.comm-comment {
  background: #171717;
  padding-top: 39px;
  padding-bottom: 44px;
  margin-top: 40px;

  .comment-box {
    max-width: 636px;
    margin: 0 auto;

    .tit-num {
      display: flex;
      align-items: center;
      font-size: 18px;
      line-height: 25px;
      font-weight: 500;
      margin-bottom: 8px;

      i {
        font-style: normal;
        margin-left: 12px;
        font-size: 12px;
        color: #EAEAEA;
        font-weight: normal;
      }
    }

    .comment-inp {
      height: 121px;
      border-radius: 16px;
      overflow: hidden;
      border: 1px solid transparent;
      transition: .1s all linear;

      &.active {
        border: 1px solid #11CCB1;
      }

      textarea {
        background: #242327;
        resize: none;
        width: 100%;
        height: 100%;
        color: #fff;
        font-size: 14px;
        line-height: 20px;
        border: none;
        padding: 11px 14px;
      }
    }

    .send-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 12px;
      margin-bottom: 24px;
      font-size: 14px;
      line-height: 28px;

      .send-btn {
        background: #11CCB1;
        color: #fff;
        text-align: center;
        width: 56px;
        user-select: none;
        border-radius: 4px;
        opacity: 1;
        transition: .1s all linear;

        &:hover {
          background: #0fab94;
        }
      }
    }

    .comments {
      .comment-data-item {
        display: flex;
        align-items: flex-start;
        margin-bottom: 20px;

        &.child {
          margin-top: 20px;
          margin-bottom: 0px;

          .uavatar {
            margin-right: 0px;
          }

          .r-con {
            padding-top: 0px;
            padding-right: 0px;

          }
        }

        .uavatar {
          width: 34px;
          height: 34px;
          min-width: 34px;
          border-radius: 34px;
          overflow: hidden;
          margin-right: 15px;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .r-con {
          background: #202020;
          border-radius: 8px;
          padding: 12px 16px;
          width: 100%;

          .view-all {
            text-align: center;

            .btn {
              color: #969696;
              font-size: 12px;
              background: url('../assets/pro/more_cmt.svg') no-repeat;
              background-position: right center;
              padding-right: 16px;
            }
          }

          .name {
            color: #BBBBBB;
            font-size: 14px;
            line-height: 20px;

            &:hover {
              color: #11CCB1;
              text-decoration: underline;
            }
          }

          .con-html {
            margin-top: 6px;
            margin-bottom: 16px;
            font-size: 16px;
          }

          .bot {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .time {
              font-size: 12px;
              color: #6E6D7A;
            }

            .funs {
              display: flex;
              align-items: center;

              a {
                // &:first-child{
                color: #BBBBBB;
                font-size: 12px;
                // width: 20px;
                height: 20px;
                // }
              }

              .reply {
                // background: url('../assets/pro/icon_reply.svg') no-repeat;
                margin-left: 20px;
                padding-left: 25px;
                background-position: center;
                transition: .1s background linear;

                &:hover {
                  color: #11CCB1;
                }
              }

              .cmt-zan {
                background: url('../assets/pro/icon_new_like.svg') no-repeat;
                margin-left: 20px;
                padding-left: 25px;
                transition: .1s background linear;
                background-position: left center;
                // margin-right: 18px;
                background-size: 20px;
                display: flex;
                align-items: center;
                justify-content: center;
                position: relative;

                &.active {
                  background: url('../assets/pro/icon_liked.svg') no-repeat;
                  background-size: 20px;
                  background-position: center;
                  background-position: left center;
                }
              }
            }
          }

          .reply-area {
            margin-top: 16px;

            .txt-area {
              position: relative;

              i {
                font-style: normal;
                position: absolute;
                right: 0px;
                bottom: 0px;
                background: #171719;
                padding-right: 5px;
                // padding:11px 13px 11px 10px;
                // border:1px solid red;
              }
            }

            textarea {
              background: #171719;
              width: 100%;
              height: 80px;
              resize: none;
              border: none;
              padding: 10px 12px;
              color: #fff;
              border-radius: 16px;
              line-height: 20px;
              display: block;
              margin-bottom: 19px;
              min-height: 110px;
            }

            .bot-area {
              display: flex;
              align-items: center;
              justify-content: space-between;

              .reply-btn {
                line-height: 28px;
                background: #11CCB1;
                border-radius: 4px;
                padding: 0px 14px;
                user-select: none;
                transition: .1s all linear;

                &:hover {
                  background: #0fab94;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>